package org.dromara.web.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSON;
import com.github.sd4324530.fastweixin.api.UserAPI;
import com.github.sd4324530.fastweixin.api.entity.UserInfo;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoListResponse;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.github.sd4324530.fastweixin.api.response.GetUsersResponse;
import com.github.sd4324530.fastweixin.api.response.Jscode2sessionResponse;
import com.github.sd4324530.fastweixin.util.WXBizDataCrypt;
import com.github.sd4324530.fastweixin.wxa.BusinessApi;
import com.github.sd4324530.fastweixin.wxa.request.CreateActivityIdReq;
import com.github.sd4324530.fastweixin.wxa.response.CreateActivityIdResponse;
import groovy.lang.Lazy;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.*;
import org.dromara.common.core.exception.BusiException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.concurrent.Async;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.common.web.context.ContextHolder;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.web.domain.vo.LoginVo;

import org.dromara.system.domain.bo.SysAccountBo;
import org.dromara.system.domain.bo.SysMemberBo;
import org.dromara.system.domain.bo.SysTenantBo;
import org.dromara.system.domain.vo.SysAccountVo;
import org.dromara.system.domain.vo.SysMemberVo;
import org.dromara.system.domain.vo.SysTenantVo;
import org.dromara.system.enums.AppCodeEnum;
import org.dromara.system.service.ISysAccountService;
import org.dromara.system.service.ISysConfigService;
import org.dromara.system.service.ISysMemberService;
import org.dromara.system.service.ISysTenantService;
import org.dromara.web.domain.vo.LoginTenantVo;
import org.dromara.web.domain.vo.TenantListVo;
import org.dromara.web.service.SysLoginService;
import org.dromara.web.service.SysRegisterService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.net.URL;
import java.util.*;

/**
 * 认证
 *
 * @author fly
 */
@SaIgnore
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(AuthController.class);
    private final SysLoginService loginService;
    private final SysRegisterService registerService;
    private final ISysConfigService configService;
    private final ISysTenantService tenantService;

    private final ISysAccountService sysAccountService;
    private final ISysMemberService sysMemberService;


    /**
     * 登录方法
     *
     * @param body 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public R<LoginVo> login(@Validated @RequestBody LoginBody body) {
        LoginVo loginVo = new LoginVo();
        // 生成令牌
        String token = loginService.login(
            body.getTenantId(),
            body.getUsername(), body.getPassword(),
            body.getCode(), body.getUuid());
        loginVo.setToken(token);
        return R.ok(loginVo);
    }

    /**
     * 短信登录
     *
     * @param body 登录信息
     * @return 结果
     */
    @PostMapping("/smsLogin")
    public R<LoginVo> smsLogin(@Validated @RequestBody SmsLoginBody body) {
        LoginVo loginVo = new LoginVo();
        // 生成令牌
        String token = loginService.smsLogin(body.getTenantId(), body.getPhonenumber(), body.getSmsCode());
        loginVo.setToken(token);
        return R.ok(loginVo);
    }

    /**
     * 邮件登录
     *
     * @param body 登录信息
     * @return 结果
     */
    @PostMapping("/emailLogin")
    public R<LoginVo> emailLogin(@Validated @RequestBody EmailLoginBody body) {
        LoginVo loginVo = new LoginVo();
        // 生成令牌
        String token = loginService.emailLogin(body.getTenantId(), body.getEmail(), body.getEmailCode());
        loginVo.setToken(token);
        return R.ok(loginVo);
    }

    /**
     * 小程序登录(测试用)
     *
     * @param body 小程序登陆信息(测试用)
     * @return 结果
     */
    @PostMapping("/xcxMappLoginByOpenId")
    public R<LoginVo> xcxMappLoginByOpenId(@Validated(AddGroup.class) @RequestBody XcxLoginBody body) {

        String appCode = request.getHeader("appCode");
        if (StringUtils.isEmpty(appCode)) {
            appCode = "mapp";
        }

        if (StringUtils.isEmpty(body.getOpenid())) {
            throw new BusiException("微信的OPEN_ID不存在");
        }

        LoginVo loginVo = new LoginVo();
        // 生成令牌
        String token = loginService.xcxMappLoginByOpenId(body.getOpenid(), appCode);
        loginVo.setToken(token);
        return R.ok(loginVo);
    }

    /**
     * 小程序登录
     *
     * @param body 小程序登陆信息
     * @return 结果
     */
    @Log(title = "小程序登录", businessType = BusinessType.INSERT)
    @PostMapping("/xcxMappLogin")
    public R<LoginVo> xcxMappLogin(@Validated(AddGroup.class) @RequestBody XcxLoginBody body) {

        String appCode = request.getHeader("appCode");
        if (StringUtils.isEmpty(appCode)) {
            appCode = "mapp";
        }

        if (StringUtils.isEmpty(body.getCode())) {
            throw new BusiException("微信的CODE不存在");
        }

        LoginVo loginVo = new LoginVo();
        // 生成令牌
        String token = loginService.xcxMappLogin(body.getCode(), appCode);
        loginVo.setToken(token);
        return R.ok(loginVo);
    }

    /**
     * 修改微信用户
     *
     * @param body 小程序修改信息
     */
    @Log(title = "微信用户", businessType = BusinessType.UPDATE)
    @org.dromara.common.idempotent.annotation.RepeatSubmit()
    @PostMapping("/updateXcxMappUser")
    public R<Void> updateByXcxUser(@Validated(EditGroup.class) @RequestBody XcxLoginBody body) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            return R.fail("用户没有登陆");
        }
        SysMemberVo user = sysMemberService.queryById(loginUser.getUserId());
        if (user == null) {
            return R.fail("请配置当前用户角色的数据权限");
        }

        SysMemberBo bo = new SysMemberBo();
        bo.setMemberId(user.getMemberId());
        if (StringUtils.isNotEmpty(body.getMobile())) {
            bo.setMobile(body.getMobile());
        }
        if (StringUtils.isNotEmpty(body.getNickname())) {
            bo.setNickname(body.getNickname());
        }
        if (StringUtils.isNotEmpty(body.getHeadImgUrl())) {
            bo.setHeadImgUrl(body.getHeadImgUrl());
        }
        boolean flag = sysMemberService.updateByBo(bo);

        return toAjax(flag);
    }

    /**
     * 获取小程序的用户信息
     *
     * @return 获取小程序的用户信息
     */
    @Log(title = "获取微信用户", businessType = BusinessType.QUERY)
    @GetMapping("/getXcxInfo")
    public R<SysMemberVo> getXcxInfo() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            return R.fail("用户没有登陆");
        }
//        log.info("userId:" + loginUser.getUserId());
        SysMemberVo user = sysMemberService.queryById(loginUser.getUserId());
        if (user == null) {
            throw new BusiException("用户ID不存在");


        }


        return R.ok(user);
    }

    /**
     * 小程序获取活动ID
     *
     * @return 结果
     */
    @Log(title = "小程序登录", businessType = BusinessType.QUERY)
    @PostMapping("/createActivityId")
    public R createActivityId() {

        String appCode = request.getHeader("appCode");
        if (StringUtils.isEmpty(appCode)) {
            appCode = "mapp";
        }

        SysAccountBo ex = new SysAccountBo();
        ex.setAppCode(appCode);
        SysAccountVo accountVo = sysAccountService.getOne(ex);
        if (accountVo == null) {
            throw new BusiException("当前应用没有配置微信账号");
        }

        LoginUser loginUser = LoginHelper.getLoginUser();
//        log.info("userId:" + loginUser.getUserId());
        SysMemberVo user = sysMemberService.queryById(loginUser.getUserId());
        if (user == null) {
            throw new BusiException("用户ID不存在");


        }
        BusinessApi businessApi = new BusinessApi(accountVo);
        CreateActivityIdResponse activityIdResponse = businessApi.createActivityId(user.getOpenId());

        return R.ok(activityIdResponse);
    }

    /**
     * 小程序绑定用户和群组关系
     *
     * @return 结果
     */
    @Log(title = "小程序绑定用户和群组关系", businessType = BusinessType.QUERY)
    @PostMapping("/bindUserGroupInfo")
    public R bindUserGroupInfo(@Validated(EditGroup.class) @RequestBody WxEncryptedDataBody body) {


        if (body.getBusiId() == null) {
            return R.ok();
        }

        String appCode = request.getHeader("appCode");
        if (StringUtils.isEmpty(appCode)) {
            appCode = "mapp";
        }

        SysAccountBo ex = new SysAccountBo();
        ex.setAppCode(appCode);
        SysAccountVo accountVo = sysAccountService.getOne(ex);
        if (accountVo == null) {
            throw new BusiException("当前应用没有配置微信账号");
        }

        LoginUser loginUser = LoginHelper.getLoginUser();
        log.info("userId:" + loginUser.getUserId());
        SysMemberVo user = sysMemberService.queryById(loginUser.getUserId());
        if (user == null) {
            throw new BusiException("用户ID不存在");
        }

        return R.ok();
    }


    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public R<Void> logout() {
        loginService.logout();
        return R.ok("退出成功");
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public R<Void> register(@Validated @RequestBody RegisterBody user) {
        if (!configService.selectRegisterEnabled(user.getTenantId())) {
            return R.fail("当前系统没有开启注册功能！");
        }
        registerService.register(user);
        return R.ok();
    }

    /**
     * 登录页面组织下拉框
     *
     * @return 组织列表
     */
    @GetMapping("/tenant/list")
    public R<LoginTenantVo> tenantList(HttpServletRequest request) throws Exception {
        List<SysTenantVo> tenantList = tenantService.queryList(new SysTenantBo());
        List<TenantListVo> voList = MapstructUtils.convert(tenantList, TenantListVo.class);
        // 获取域名
        String host = new URL(request.getRequestURL().toString()).getHost();
        // 根据域名进行筛选
        List<TenantListVo> list = StreamUtils.filter(voList, vo -> StringUtils.equals(vo.getDomain(), host));
        // 返回对象
        LoginTenantVo vo = new LoginTenantVo();
        vo.setVoList(CollUtil.isNotEmpty(list) ? list : voList);
        vo.setTenantEnabled(false);
        return R.ok(vo);
    }

}
